package club.looli.haoke.api.service;

import club.looli.haoke.api.vo.PicUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;

/**
 * <p>
 * Created by looli on 2020/7/8
 * </p>
 *
 * <p>
 * 本地文件上传
 * </p>
 *
 * @author looli
 * @since 2020/7/8
 */
@Service
public class PicUploadFileSystemService {
    /**
     * 允许上传的格式
     */
    private static final String[] IMAGE_TYPE =
            new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};

    /**
     * 文件上传
     * @param uploadFile
     * @return PicUploadResult
     */
    public PicUploadResult upload(MultipartFile uploadFile) {
        //封装Result对象，并且将文件的byte数组放置到result对象中
        PicUploadResult fileUploadResult = new PicUploadResult();

        //校验文件格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {
                isLegal = true;
                break;
            }
        }

        //文件不符合格式，直接返回错误
        if(!isLegal){
            fileUploadResult.setStatus("error");
            fileUploadResult.setResponse("文件格式不正确");
            return fileUploadResult;
        }
        // 文件新路径
        String fileName = uploadFile.getOriginalFilename();
        String filePath = getFilePath(fileName);

        File newFile = new File(filePath);
        // 上传到本地
        try {
            uploadFile.transferTo(newFile);
        } catch (Exception e) {
            e.printStackTrace();
            //上传失败
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }
        String dir = baseDir();
        String baseFolder = dir+"code\\looli-haoke\\haoke-upload";
        baseFolder.replace("\\",File.separator);
        String picUrl = StringUtils.replace(StringUtils.substringAfter(filePath, baseFolder), File.separator, "/");
        fileUploadResult.setName("http://image.haoke.com" + picUrl);
        fileUploadResult.setStatus("done");
        fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return fileUploadResult;
    }

    /**
     * 设置文件路径
     * @param sourceFileName
     * @return 文件路径
     */
    private String getFilePath(String sourceFileName) {
        String dir = baseDir();
        String baseFolder = dir+"code\\looli-haoke\\haoke-upload" + File.separator
                + "images"+ File.separator;
        baseFolder.replace("\\",File.separator);
        DateTime dateTime = new DateTime();
        String fileFolder =  baseFolder + dateTime.toString("yyyy")
                + File.separator + dateTime.toString("MM") + File.separator
                + dateTime.toString("dd")  ;
        File file = new File(fileFolder);
        if (!file.isDirectory()) {
            // 如果目录不存在，则创建目录
            file.mkdirs();
        }
        // 生成新的文件名
        String fileName = new DateTime(dateTime).toString("yyyyMMddhhmmssSSSS") + RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");

        return fileFolder + File.separator + fileName;
    }

    private String baseDir(){
        String separator = java.io.File.separator;
        //windows
        if ("\\".equals(separator)){
            String property = System.getProperty("user.dir");
            String substring = property.substring(0, 3);
            return substring;
        }else {//linux
           return "/";
        }
    }
}
